"""
Case Type   : 资源池化集群DMS reform优化
Case Name   : 主备启动tpcc业务->cm_ctl stop -n 1 -I 6001->failover完成
Create At   : 2024/05/13
Owner       : @kyleze
Description :
    1.主备启动tpcc业务
    2.cm_ctl stop -n 1 -I 6001
    3.查看集群状态
Expect      :
    1.成功
    2.成功
    3.集群状态正常
History     :
"""

import os
import unittest
import time

from testcase.utils.Constant import Constant
from testcase.utils.Logger import Logger
from testcase.utils.Common import Common
from testcase.utils.CommonSH import CommonSH
from testcase.utils.ComThread import ComThread

from yat.test import Node
from yat.test import macro


class DmsRform(unittest.TestCase):
    def setUp(self):
        self.log = Logger()
        self.log.info(f'----{os.path.dirname(__file__)} start----')
        self.com = Common()
        self.constant = Constant()
        self.primary_sh = CommonSH("PrimaryDbUser")
        self.pri_user_node = Node(node="PrimaryDbUser")
        self.st1_user_node = Node(node="Standby1DbUser")
        self.st2_user_node = Node(node="Standby2DbUser")

    def test_dms(self):
        step = '--step1:主备启动tpcc业务 expect:成功--'
        self.log.info(step)
        tpcc_cmd = f'. runBenchmark.sh {macro.TPCC_PROPS_FILENAME}'
        tpcc_thread = ComThread(
            self.com.start_tpcc,
            args=(Node(node='PrimaryRoot'), macro.TPCC_PATH, tpcc_cmd,))
        tpcc_thread.setDaemon(True)
        tpcc_thread.start()
        self.log.info('--备1执行tpcc读业务--')
        tpcc_cmd = f'. runBenchmark.sh {macro.TPCC_PROPS_FILENAME_ST1}'
        st1_tpcc_thread = ComThread(
            self.com.start_tpcc,
            args=(Node(node='PrimaryRoot'), macro.TPCC_PATH, tpcc_cmd,))
        st1_tpcc_thread.setDaemon(True)
        st1_tpcc_thread.start()
        self.log.info('--备2执行tpcc读业务--')
        tpcc_cmd = f'. runBenchmark.sh {macro.TPCC_PROPS_FILENAME_ST2}'
        st2_tpcc_thread = ComThread(
            self.com.start_tpcc,
            args=(Node(node='PrimaryRoot'), macro.TPCC_PATH, tpcc_cmd,))
        st2_tpcc_thread.setDaemon(True)
        st2_tpcc_thread.start()

        step = '--step2:踢出主机 expect:成功--'
        self.log.info(step)
        result = self.primary_sh.exec_cm_ctl("stop", '-n 1 -I 6001')
        self.log.info(result)
        self.assertIn(self.constant.cm_stop_node_success_msg, "执行失败" + step)

        step = '--step3:查看集群状态 expect:集群状态正常--'
        self.log.info(step)
        time.sleep(20)
        status = self.primary_sh.get_db_cluster_status('status')
        self.assertTrue("Degraded" in status, "执行失败" + step)

    def tearDown(self):
        self.log.info('--还原环境--')
        start_res = self.primary_sh.exec_cm_ctl("start", '-n 1 -I 6001')
        switchover_res = self.primary_sh.exec_cm_ctl('switchover', '-a')
        self.log.info(start_res)
        self.log.info(switchover_res)
        self.assertTrue(start_res, '启动主机失败')
        self.assertTrue(switchover_res, "环境还原失败")
        self.log.info(f'----{os.path.dirname(__file__)} end----')
